package com.atuguigu.flink.Day03;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;

// 水位线概念
public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .socketTextStream("localhost",9999)
                .map(
                        new MapFunction<String, Tuple2<String,Long>>() {


                            @Override
                            public Tuple2<String, Long> map(String s) throws Exception {
                                String[] arr = s.split(" ");

                                return Tuple2.of(arr[0],Long.parseLong(arr[1] ) * 1000L);
                            }
                        }
                )
                // 水位线插入逻辑：告诉flink哪一个字段是时间戳；最大延迟时间是多少；
                // 针对乱序流：`forBoundedOutOfOrderness`
                // 最大延迟时间设置为5s：Duration.ofSeconds(5)
                // 水位线 = 观察到的最大时间戳 - 最大延迟时间 - 1毫秒
                // 默认每隔200ms的机器时间插入一次水位线
                .assignTimestampsAndWatermarks(WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                    //
                    @Override
                    public long extractTimestamp(Tuple2<String, Long> stringLongTuple2, long l) {
                        return stringLongTuple2.f1;//告诉flink时间戳是f1字段
                    }
                }))
                .keyBy(r->r.f0)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<Tuple2<String, Long>> iterable, Collector<String> collector) throws Exception {
                        long counts=0L;
                        for(Tuple2<String,Long> e:iterable){
                            counts += 1L;
                        }
                        String windowStart = new Timestamp(context.window().getStart()).toString();
                        String windowEnd = new Timestamp(context.window().getEnd()).toString();
                        collector.collect(windowStart + "==>" + windowEnd +"窗口总共" + counts  + "条元素");
                    }
                })
                .print();







        env.execute();
    }
}
